package portal.web.delegate;

import java.util.Hashtable;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

public class ServiceLocator {

	private static Hashtable<String, Object> tabla;

	public static <T> T getService(String jndiName, Class<T> clazz) {
		try {
			if (tabla == null) {
				tabla = new Hashtable<String, Object>();
			}

			Object obj = tabla.get(jndiName);
			if (obj == null) {
				final String appName = "tpoPortalEAR";
				final String moduleName = "tpoPortalEJB";
				final String sessionBeanName = jndiName;
				final String viewClassName = clazz.getName();
				Context ctx = getInitialContext();
				obj = ctx.lookup("ejb:" + appName + "/" + moduleName + "/"
						+ sessionBeanName + "!" + viewClassName);

				tabla.put(jndiName, obj);
			}
			return clazz.cast(obj);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
	}

	private static Context getInitialContext() throws Exception {
		Properties jndiProps = new Properties();
		jndiProps.put(Context.INITIAL_CONTEXT_FACTORY,
				"org.jboss.as.naming.InitialContextFactory");
		jndiProps.put(Context.PROVIDER_URL, "remote://127.0.0.1:4447");
		// username
		jndiProps.put(Context.SECURITY_PRINCIPAL, "test");
		// password
		jndiProps.put(Context.SECURITY_CREDENTIALS, "test-123");
		jndiProps.put("jboss.naming.client.ejb.context", true);
		return new InitialContext(jndiProps);
	}
}
